package com.base.controller.wx_mp_api;

import com.base.helper.WebHelper;
import com.base.po.param.NetState;
import com.base.po.voip.UsersConfig;
import com.base.po.wx.WXJsSdkTicket;
import com.base.service.UsersConfigService;
import com.base.utils.PayCommonUtil;
import com.base.utils.Produce;
import com.base.utils.SHA1Util;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * 微信接口
 *
 * @author K.
 */
@Slf4j
@Controller
@RequestMapping("/weixin")
public class Wx_Js_SdkController {

    private final UsersConfigService usersConfigService;

    private final Wx_TokenController wx_tokenController;

    public Wx_Js_SdkController(UsersConfigService usersConfigService, Wx_TokenController wx_tokenController) {
        this.usersConfigService = usersConfigService;
        this.wx_tokenController = wx_tokenController;
    }

    /**
     * 微信 - Js_Sdk使用权限签名
     */
    @RequestMapping(value = "/jsSdkSign", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState jsSdkSign(HttpServletRequest request, String parentId, String url) {
        NetState netState = new NetState();
        log.warn("[拼团]微信授权参数parentid={},url={}:",parentId,url);
        if (parentId == null || parentId.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        // 代理商
        UsersConfig config = null;
        String appId = null;
        String secret = null;
        try {
            config = usersConfigService.selectByParentId(parentId);
            appId = config.getWxMpAppid();
            secret = config.getWxMpAppsecret();
        }catch (Exception e){
            netState.setErrorCode(NetState.NODATA);
            netState.setData("数据异常");
            return netState;
        }

        String accessToken = wx_tokenController.getTokeFromRedis(appId, secret);
        String nonceStr = PayCommonUtil.getRandomString(32);
        Long timestamp = Produce.getNowDate().getTime()/1000;
        String signUrl = url;
        try {
            Map<String, Object> ticketMap = this.getJsApiTicket(accessToken);
            String ticket = (String)ticketMap.get("ticket");
            if (ticket != null && !ticket.equals("")){
                String params = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + signUrl;

                Map<String, Object> map = new HashedMap();
                map.put("sign", SHA1Util.getSha1(params));
                map.put("timestamp", timestamp);
                map.put("nonceStr", nonceStr);

                netState.setErrorCode(NetState.SUCCESS_CONN);
                netState.setData("签名成功");
                netState.setJson(map);
                log.warn("签名返回结果result={}",ticketMap.toString());
            }else {
                netState.setErrorCode(NetState.SYSTEM_ERROR);
                netState.setData("签名失败,无效ticket");
                log.warn("签名返回结果result={}","签名失败,无效ticket");
            }
        }catch (Exception e){
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("签名失败,无效token");
            log.warn("签名返回结果result={}","签名失败,无效token");
        }

        return netState;
    }

    public Map<String, Object> getJsApiTicket(String accessToken){
        Map<String, Object> map = new HashedMap();

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        try {
            String result = WebHelper.PostData(tokenUrl, null, null, null);
            WXJsSdkTicket ticket = (WXJsSdkTicket) JSONObject.toBean(JSONObject.fromObject(result), WXJsSdkTicket.class);
            map.put("ticket", ticket.getTicket());
        }catch (Exception e){
            map = null;
        }

        return map;
    }
}
